//
// Created by Administrator on 2021/4/5.
//

#include <vector>
#include <iostream>
#include <stack>

using namespace std;

//  Definition for a binary tree node.
// 树节点定义
struct TreeNode {
    int val; // 节点值
    TreeNode *left; // 左子节点
    TreeNode *right; // 右子节点

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    void inorder(TreeNode *t, vector<int> &v) { // 递归函数
        if (t == nullptr) {
            return;
        }
        inorder(t->left, v);
        v.push_back(t->val);
        inorder(t->right, v);
    }

    vector<int> inorderTraversal(TreeNode *root) { // 递归解法
        vector<int> ans;
        inorder(root, ans);
        return ans;
    }
};

class Solution2 { //  迭代
public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        if (root == nullptr) {
            return res;
        }

        stack<TreeNode *> stk;  // 显式维护一个栈 递归中用的是递归栈
        TreeNode *node = root;
        while (!stk.empty() || node != nullptr) {
            while (node != nullptr) {
                stk.push(node);
                node = node->left;
            }
            node = stk.top();
            stk.pop(); // 弹栈
            res.push_back(node->val); // 保存结果
            node = node->right;
        }
        return res;
    }
};

// 二叉树的中序遍历 左  中   右
int main() {
//    [ 1, 4, 2, 3 ];
    auto t4 = TreeNode(4);
    auto t3 = TreeNode(3);
    TreeNode t2 = TreeNode(2, &t3, nullptr);
    TreeNode t1 = TreeNode(1, &t4, &t2);
//    auto sol = Solution();
    auto sol = Solution2();
    vector<int> ans = sol.inorderTraversal(&t1);
//    vector<int> ans =
    for (auto x:ans) {
        cout << x << endl;
    }
    return 0;
}
